﻿using log4net.Core;
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Windows.Threading;

namespace HobSoft.SoccerBet2014.Client.ViewModels
{
    public class LogShellModel : ViewModelBase, IDisposable
    {
        private ObservableCollection<LoggingEvent> loggingList;
        private DispatcherTimer timer = new DispatcherTimer();

        public LogShellModel()
        {
            loggingList = new ObservableCollection<LoggingEvent>();
            loggingList.CollectionChanged += Logging_CollectionChanged;
            LoggingCollecton = new ReadOnlyObservableCollection<LoggingEvent>(loggingList);
            timer.Tick += Timer_Tick;
            timer.Interval = TimeSpan.FromMilliseconds(300);
            timer.Start();
            Log.ApplicationCacheLogAppender.Singleton.AddCacheCollection(loggingList, 10, lg => true);
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            if (!LoggingCollecton.Any())
                return;
            var lastTime = LoggingCollecton.Max(lg => lg.TimeStamp);
            HasNewLog = (DateTime.Now - lastTime).TotalMilliseconds < 5000;
        }

        private void Logging_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add
                || e.Action == NotifyCollectionChangedAction.Replace)
            {
                HasNewLog = true;
            }
        }

        private bool _hasNewLog;

        public bool HasNewLog
        {
            get { return _hasNewLog; }
            set { PropertyValueChange(ref _hasNewLog, value, "HasNewLog"); }
        }

        private ReadOnlyObservableCollection<LoggingEvent> _loggingCollection;

        public ReadOnlyObservableCollection<LoggingEvent> LoggingCollecton
        {
            get { return _loggingCollection; }
            set { PropertyValueChange(ref _loggingCollection, value, "LoggingCollecton"); }
        }


        public void Dispose()
        {
            if (timer != null)
            {
                timer.Stop();
            }
        }
    }
}
